<template>
    <!-- 新增/编辑用户 -->
    <el-drawer
        v-model="userParams.visible"
        :title="dialogTitle"
        @open="handleOpen"
        size="1200"
        :close-on-click-modal="true"
    >
        <!-- {{ formData }} -->
        <div class="drawer-main" v-loading="loading">
            <div class="topFrom">
                <div class="titel">基础信息</div>
                <el-form
                    ref="ruleFormRef"
                    :model="formData"
                    :rules="rules"
                    label-width="120"
                >
                    <el-row gutter="20">
                        <!-- 姓名 -->
                        <el-col :span="11">
                            <el-form-item label="姓名" prop="userName">
                                <el-input
                                    v-model.trim="formData.userName"
                                    disabled
                                    maxlength="150"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <!-- 职位 -->
                        <el-col :span="11">
                            <el-form-item label="职位" prop="position">
                                <el-input
                                    v-model.trim="formData.position"
                                    disabled
                                    maxlength="150"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>
                        <!-- 部门 -->
                        <el-col :span="22">
                            <el-form-item label="部门" prop="deptName">
                                <el-input
                                    v-model.trim="formData.deptName"
                                    disabled
                                    maxlength="150"
                                    clearable
                                />
                            </el-form-item>
                        </el-col>

                        <!-- 修改角色名 -->
                        <!-- <el-col :span="11">
                        <el-form-item label="修改角色名" prop="roleIds">
                            <el-select
                                v-model="formData.roleIds"
                                multiple
                                collapse-tags
                                collapse-tags-tooltip
                                :max-collapse-tags="3"
                                placeholder="请选择角色"
                            >
                                <el-option
                                    v-for="item in roleOptions"
                                    :key="item.roleId"
                                    :label="item.roleName"
                                    :value="item.roleId"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col> -->
                    </el-row>
                </el-form>
            </div>
            <!-- 表格 -->
            <div class="tableConeten">
                <div class="titel">角色列表</div>
                <div class="titleFrom">
                    <el-form
                        ref="ruleFormRefJuese"
                        :model="formDataJueSe"
                        :rules="rulesJueSe"
                        label-width="80"
                    >
                        <el-row gutter="22">
                            <!-- 修改角色名 -->
                            <el-col :span="6">
                                <el-form-item label="角色名" prop="roleIds">
                                    <el-select
                                        v-model="formDataJueSe.roleIds"
                                        collapse-tags
                                        collapse-tags-tooltip
                                        :max-collapse-tags="3"
                                        placeholder="请选择"
                                    >
                                        <el-option
                                            v-for="item in roleOptions"
                                            :key="item.roleId"
                                            :label="item.roleName"
                                            :value="item.roleId"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <!-- 开始时间 -->
                            <el-col :span="6">
                                <el-form-item label="起始时间" prop="startTime">
                                    <el-date-picker
                                        v-model="formDataJueSe.startTime"
                                        type="date"
                                        placeholder="开始日期"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <!-- 结束时间 -->
                            <el-col :span="6">
                                <el-form-item label="结束时间" prop="endTime">
                                    <el-date-picker
                                        v-model="formDataJueSe.endTime"
                                        type="date"
                                        placeholder="结束日期"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                            <!-- 操作 -->
                            <el-col :span="4">
                                <el-button type="primary" @click="addList">
                                    新增
                                </el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="tablePadding">
                    <el-table
                        v-loading="tableLoading"
                        :data="tableData"
                        highlight-current-row
                        border
                    >
                        <!-- 序号列 -->
                        <el-table-column
                            label="序号"
                            type="index"
                            width="60"
                            fixed
                            align="center"
                        >
                        </el-table-column>
                        <el-table-column
                            v-for="(item, index) in columnData"
                            :key="index"
                            :prop="item.prop"
                            :label="item.label"
                            :width="item.width || ''"
                            :fixed="item.fixed || false"
                            show-overflow-tooltip
                            :resizable="false"
                            align="center"
                        >
                            <template #default="{ row }">
                                <span v-if="item.prop === 'expireStatus'">
                                    <el-tag
                                        v-if="row[item.prop] === 'normal'"
                                        type="success"
                                        effect="dark"
                                    >
                                        正常
                                    </el-tag>
                                    <el-tag
                                        v-else-if="row[item.prop] === 'expired'"
                                        type="danger"
                                        effect="dark"
                                    >
                                        已过期
                                    </el-tag>
                                </span>
                                <span v-else>{{ row[item.prop] }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="100">
                            <template #default="scope">
                                <el-button
                                    type="danger"
                                    icon="Delete"
                                    link
                                    @click="handleDelete(scope.row)"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <Pagination
                        v-if="total > 0"
                        v-model:total="total"
                        v-model:page="queryParams.pageNo"
                        v-model:limit="queryParams.pageSize"
                        @pagination="AddTableList"
                    />
                </div>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emit('close')">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </div>
        </template>
    </el-drawer>
</template>

<script setup>
import { reactive, ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    getUserRoleList,
    postOrUpdateUser
} from '@views/userManage/api/userManage'
import { getRolePage } from '@views/roleManage/api/roleManage'

const props = defineProps({
    userParams: {
        type: Object,
        default: () => {},
        required: true
    }
})

const emit = defineEmits(['close'])
const formData = reactive({})
const ruleFormRef = ref(null)
const loading = ref(false)
const dialogTitle = '编辑权限'
const rules = reactive({
    // userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
})
// ref="ruleFormRefJuese"
//                     :model="formDataJueSe"
//                     :rules="rulesJueSe"
const ruleFormRefJuese = ref(null)
const formDataJueSe = reactive({})
// 自定义验证结束时间
const validateEndTime = (rule, value, callback) => {
    if (value && formDataJueSe.startTime) {
        const startTime = new Date(formDataJueSe.startTime)
        const endTime = new Date(value)
        if (endTime < startTime) {
            callback(new Error('结束时间不能小于开始时间'))
            formDataJueSe.endTime = ''
        } else {
            callback()
        }
    } else {
        callback()
    }
}
const rulesJueSe = reactive({
    roleIds: [{ required: true, message: '请输入角色名', trigger: 'change' }],
    startTime: [{ required: true, message: '请输入开始时间', trigger: 'blur' }],
    endTime: [
        { required: true, message: '请输入结束时间', trigger: 'blur' },
        { validator: validateEndTime, trigger: 'blur' }
    ]
})
const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}

// 表格
const tableLoading = ref(false)
const tableData = ref([])
const total = ref(0)
const queryParams = reactive({
    pageNo: 1,
    pageSize: 10
})
const columnData = ref([
    {
        label: '角色名',
        prop: 'roleName',
        fixed: 'left'
    },
    {
        label: '角色编码',
        prop: 'roleCode'
    },
    {
        label: '起始时间',
        prop: 'startTime'
    },
    {
        label: '结束时间',
        prop: 'endTime'
    },
    {
        label: '状态',
        prop: 'expireStatus'
    }
])
const addList = () => {
    ruleFormRefJuese.value.validate((valid) => {
        if (valid) {
            // 创建新的角色数据对象
            const newRoleData = {
                roleId: selectedRoles.value[0].roleId,
                roleName: selectedRoles.value[0].roleName,
                roleCode: selectedRoles.value[0].roleCode,
                startTime: formatTimestamp(formDataJueSe.startTime),
                endTime: formatTimestamp(formDataJueSe.endTime)
            }

            // 通过深拷贝确保数据的独立性，避免引用相同对象
            const deepCopyRoleData = JSON.parse(JSON.stringify(newRoleData))

            // 如果没有重复数据，则推入 tableData
            const isDuplicate = tableData.value.some(
                (item) => item.roleId === deepCopyRoleData.roleId
            )

            if (!isDuplicate) {
                tableData.value.push(deepCopyRoleData)
            } else {
                ElMessage.warning('重复数据，不能添加!')
            }

            console.log(tableData.value)
            // formDataJueSe = reactive({})
        } else {
            return false
        }
    })
}
// 删除单行
const handleDelete = (row) => {
    // 使用 findIndex 找到数组中目标数据的索引
    let index = tableData.value.findIndex((item) => item.roleId === row.roleId)

    // 如果找到该数据，删除该数据
    if (index !== -1) {
        ElMessageBox.confirm('确认删除的数据项', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
            .then(() => {
                tableData.value.splice(index, 1)
                ElMessage.warning('删除成功，请保存数据！')
            })
            .catch(() => {})
    }
}
const handleSubmit = () => {
    handleSave()
}
const handleSave = async () => {
    try {
        let obj = {
            userId: props.userParams.row.userId,
            userRoleList: tableData.value
        }
        loading.value = true
        const res = await postOrUpdateUser(obj)
        if (res?.code === 200) {
            ElMessage.success('保存成功')
            emit('close', true)
        }
    } catch (error) {
        console.error('Request error:', error)
    }
    loading.value = false
}
const roleOptions = ref([])
const getRoleData = async () => {
    loading.value = true
    const res = await getRolePage({ pageNo: 1, pageSize: 10000 })
    loading.value = false
    if (res?.code === 200) {
        roleOptions.value = res.data.records || []
    }
}
const AddTableList = async () => {
    let obj = {
        userId: props.userParams.row.userId,
        pageNo: 1,
        pageSize: 10
    }
    try {
        const res = await getUserRoleList(obj)
        if (res.code === 200) {
            tableData.value = res.data.records
            // 使用 resetFields 清空表单数据和校验状态
            ruleFormRefJuese.value.resetFields()
        }
    } catch (error) {
        console.error('Request error:', error)
    }
}
// 计算属性：根据选择的 roleIds 获取选中的角色对象
const selectedRoles = computed(() => {
    return roleOptions.value.filter((role) =>
        formDataJueSe.roleIds.includes(role.roleId)
    )
})

// 初始化弹窗
const handleOpen = () => {
    AddTableList()
    getRoleData()
    nextTick(() => {
        ruleFormRef.value.resetFields()
        // deptOptions.value = props.userParams.deptOptions

        let row = props.userParams.row
        // 编辑
        formData.userId = row.userId
        formData.userName = row.userName
        formData.position = row.position
        formData.deptName = row.deptName
        formData.deptId = row.deptId
        console.log('初始化')
    })
}
</script>

<style lang="less" scoped>
.titel {
    width: 100%;
    height: 60px;
    padding: 0 10px;
    line-height: 60px;
    color: #0a0a0a;
    font-weight: 600;
    font-size: 14px;
    position: relative;
}
.titel::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 20px;
    width: 5px;
    border-radius: 10px;
    background-color: #1943ff;
}
.titleFrom {
    width: 100%;
}
.tablePadding {
    padding: 0 20px;
}
</style>
